package com.atguigu.spzx.cart.service.impl;

import com.alibaba.fastjson2.JSON;
import com.atguigu.spzx.cart.service.CartService;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.feign.product.ProductFeignClient;
import com.atguigu.spzx.model.entity.h5.CartInfo;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.utils.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    private String getCartKey(Long userId) {
        //定义key user:cart:userId
        return "user:cart:" + userId;
    }

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        //1.操作购物车,需要在登录状态进行
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        if (null == userInfo) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        String cartKey = this.getCartKey(userInfo.getId());
        //2.获取购物车信息
        Object cartInfoObj = redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId));
        CartInfo cartInfo = null;
        if (cartInfoObj != null) {
            //3.如果当前商品存在,进进行增加数量
            cartInfo = JSON.parseObject(cartInfoObj.toString(), CartInfo.class);
            cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum);
            cartInfo.setUpdateTime(new Date());
            cartInfo.setIsChecked(1); //选中状态

        } else {

            // 当购物车中没用该商品的时候，则直接添加到购物车！
            cartInfo = new CartInfo();

            // 购物车数据是从商品详情得到 {skuInfo}
            ProductSku productSku = productFeignClient.getBySkuId(skuId);
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuNum(skuNum);
            cartInfo.setSkuId(skuId);
            cartInfo.setUserId(userInfo.getId());
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);
            cartInfo.setCreateTime(new Date());
            cartInfo.setUpdateTime(new Date());
        }
        //4.如果商品不存在直接添加当前商品

        redisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), JSON.toJSONString(cartInfo));


    }

    @Override
    public List<CartInfo> getCartList() {
        //获取列表
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        if (null == userInfo) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        String cartKey = this.getCartKey(userInfo.getId());
        //获取redis数据列表
        List<Object> values = redisTemplate.opsForHash().values(cartKey);
        if (!CollectionUtils.isEmpty(values)) {
            //购物车不为空
            List<CartInfo> infoList = values.stream().map(item -> JSON.parseObject(item.toString(), CartInfo.class))
                    .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                    .collect(Collectors.toList());
            return infoList;
        }
        return new ArrayList<CartInfo>();
    }

    @Override
    public void deleteCart(Long skuId) {
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        if (null == userInfo) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        String cartKey = this.getCartKey(userInfo.getId());
        redisTemplate.opsForHash().delete(cartKey, String.valueOf(skuId));
    }

    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        //更新选中状态的值
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        if (null == userInfo) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        String cartKey = this.getCartKey(userInfo.getId());
        Object cartInfo = redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId));
        //判断是否存在当前对象
        Boolean hasKey = redisTemplate.opsForHash().hasKey(cartKey, String.valueOf(skuId));
        if (hasKey) {
            CartInfo info = JSON.parseObject(cartInfo.toString(), CartInfo.class);
            info.setIsChecked(isChecked);
            redisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), JSON.toJSONString(info));
        }
    }

    @Override
    public void allCheckCart(Integer isChecked) {
        //全选,全不选
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        if (null == userInfo) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        String cartKey = this.getCartKey(userInfo.getId());
        //获取所有redis的数据
        List<Object> values = redisTemplate.opsForHash().values(cartKey);
        if (!CollectionUtils.isEmpty(values)) {
            //不为空
            List<CartInfo> cartInfoList = values.stream().map(item -> JSON.parseObject(item.toString(), CartInfo.class)).collect(Collectors.toList());
            //将集合对象中的数据进行操作
            cartInfoList.forEach(cartInfo -> redisTemplate.opsForHash().put(cartKey, String.valueOf(cartInfo.getSkuId()), JSON.toJSONString(cartInfo)));

        }
    }

    @Override
    public void clearCart() {
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        if (null == userInfo) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        String cartKey = this.getCartKey(userInfo.getId());
        redisTemplate.delete(cartKey);
    }

    @Override
    public List<CartInfo> getAllCkecked() {

        UserInfo userInfo = AuthContextUtil.getUserInfo();
//        if (null == userInfo) {
//            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
//        }
        String cartKey = this.getCartKey(userInfo.getId());
        //获取数据
        List<Object> values = redisTemplate.opsForHash().values(cartKey);
        if (!CollectionUtils.isEmpty(values)) {
            //不为空,将获取所有数据
            //将json对象转换为cartInfo
            List<CartInfo> cartInfoList = values.stream().map(item -> JSON.parseObject(item.toString(), CartInfo.class)).filter(cartInfo -> cartInfo.getIsChecked() == 1).collect(Collectors.toList());
            return cartInfoList;
        }
        return new ArrayList<>();
    }

    @Override
    public void deleteChecked() {
        Long userId = AuthContextUtil.getUserInfo().getId();
        String cartKey = getCartKey(userId);

        List<Object> objectList = redisTemplate.opsForHash().values(cartKey);

        if(!CollectionUtils.isEmpty(objectList)) {
            List<CartInfo> collect = objectList.stream().map(item -> JSON.parseObject(item.toString(), CartInfo.class)).filter(item -> item.getIsChecked() == 1).collect(Collectors.toList());
            //获取被选中的对象
            collect.forEach(cartInfo -> redisTemplate.opsForHash().delete(cartKey,cartInfo.getSkuId().toString()));
        }
    }
}





























